﻿using SumPower.MailAccount.Web.Models;
using SumPower.MailAccount.Web.XMail263Service;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Xml;

namespace SumPower.MailAccount.Web.Controllers
{
    [AllowAnonymous]
    public class SamplesController : Controller
    {
        private readonly string key;
        private readonly string domain;
        private readonly string account;
        public SamplesController()
        {
            key = ConfigurationManager.AppSettings["key"];
            domain = ConfigurationManager.AppSettings["domain"];
            account = ConfigurationManager.AppSettings["account"];
        }
        public ActionResult Search(string id)
        {
            var list = GetUserInfos();
            if (!string.IsNullOrEmpty(id))
            {
                list = list.Where(u => u.Name.Contains(id)).ToList();
            }
            list = list.Distinct().ToList();
            return Json(list, JsonRequestBehavior.AllowGet);

        }
        private List<UserInfo> GetUserInfos()
        {
            List<UserInfo> list = new List<UserInfo>();

            XmapiImplService xmapiImplService = new XmapiImplService();

            string sign = Md5Sign(domain + account + key);
            //263验证登录，返回0成功，其他失败
            var result = xmapiImplService.getDomainUserlist_New(domain, account, sign);
            if (!string.IsNullOrEmpty(result))
            {
                XmlDocument xmlDocument = new XmlDocument();
                xmlDocument.LoadXml(result);
                foreach (XmlNode userNode in xmlDocument.DocumentElement.ChildNodes)
                {
                    UserInfo user = new UserInfo();

                    user.Userid = userNode["userid"].InnerText;
                    user.Name = userNode["name"].InnerText;
                    user.Departmentid = userNode["departmentid"].InnerText;
                    user.Office = userNode["office"].InnerText;
                    user.Mobile = userNode["mobile"].InnerText;
                    user.Phone = userNode["phone"].InnerText;
                    user.Fax = userNode["fax"].InnerText;
                    list.Add(user);
                }
            }
            return list;
        }

        private string Md5Sign(string value)
        {
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] buffer = Encoding.Default.GetBytes(value);
            string result = BitConverter.ToString(md5.ComputeHash(buffer));
            return result.Replace("-", "").ToLower();

        }
    }
}